<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox, genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import appStore from '@/store'
const { token } = appStore.useUser
const upload = ref<UploadInstance>()
const emit = defineEmits(['update'])

defineProps({
  apiAddress: {
    type: String,
    default: ''
  }
})

// 批量导入对话框控制
const dialogFormVisible = ref(false)
//const address = ref('')

// 导入excel
//将open函数暴露给父组件，并初始化弹窗数据，如果使用父子传参传递信息，会有异步的问题
const open = () => {
  dialogFormVisible.value = true
  // console.log(apiAddress)
  // address.value = apiAddress
}

defineExpose({
  open
})

//一次只能上传一个excel，替换上一个
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

// 退出刷新弹窗
const handleBack = () => {
  // 清空
  upload.value!.clearFiles()
  dialogFormVisible.value = false
}

//提交函数
const submitUpload = () => {
  ElMessageBox.confirm('您确认导入吗？id相同的数据将被覆盖', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 提交
    upload.value!.submit()
  })
}

//上传错误处理
const handleError = (err: any) => {
  ElMessage.error(err)
}

//上传成功函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //这里获得上传成功返回的图片url
  if (response.code == 200) {
    ElMessage.success('上传成功')
    // 清空
    upload.value!.clearFiles()
    //刷新表格数据
    emit('update')
    dialogFormVisible.value = false
  } else {
    ElMessage.error(response.msg)
    dialogFormVisible.value = false
    upload.value!.clearFiles()
  }
}
</script>

<template>
  <el-dialog v-model="dialogFormVisible" title="上传excel" width="40%">
    <el-upload
      drag
      ref="upload"
      class="upload-demo"
      :action="apiAddress"
      :limit="1"
      :on-exceed="handleExceed"
      :on-success="handleAvatarSuccess"
      :on-error="handleError"
      :auto-upload="false"
      :headers="{
        token: token
      }"
    >
      <el-icon class="el-icon--upload"><Plus /></el-icon>
      <div class="el-upload__text">点击或拖拽文件到此处上传</div>
      <div class="el-upload__text">一次只能上传一个excel文件</div>
      <div class="el-upload__text" style="color: red">id相同的数据将被覆盖</div>
      <!-- <el-button class="ml-3" type="success" @click="submitUpload"> upload to server </el-button> -->
      <!-- <template #tip>
        <div class="el-upload__tip text-red">limit 1 file, new file will cover the old file</div>
      </template> -->
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleBack">取消</el-button>
        <el-button type="primary" @click="submitUpload">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
